package core

import (
	"context"
	"software/global"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// InitMongoDB 初始化MongoDB连接
func InitMongoDB() error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 连接MongoDB
	clientOptions := options.Client().ApplyURI(global.Config.MongoDB.ConnectionString)
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		return err
	}

	// 验证连接
	err = client.Ping(ctx, nil)
	if err != nil {
		return err
	}

	//global.MongoDB = client
	global.MongoDBC = client.Database(global.Config.MongoDB.Database)

	global.Log.Info("MongoDB连接成功!")
	return nil
}
